<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Member_Order_Compute{

    /**
     * @param $ordersn
     * @param $type
     * @return false
     * @throws Kohana_Exception
     * 下单时直接算出各渠道总收益
     */
    public static function add($ordersn, $type=false)
    {
        //订单信息
        $order_info = DB::select()->from('member_order')->where("ordersn={$ordersn}")->execute()->current();
        //检测是否计算过订单信息.
        if(self::is_computed($order_info['id']))
        {
            return false;
        }

        $total_price = Model_Member_Order::order_total_price($order_info['id'],$order_info);
        $order_info['total_price'] = $total_price;
        //定金总价
        $num = $order_info['dingnum'] + $order_info['childnum'] + $order_info['oldnum']+$order_info['people4_num']+$order_info['people5_num']+$order_info['people6_num'];
        $subscription_price = $order_info['dingjin'] ? $order_info['dingjin'] * $num : 0;
        //添加供应商佣金记录
        if($order_info['supplierlist'] && $order_info['typeid']!=104){
            $commission_info = self::caculate_platform_commission($order_info, $total_price);
            if(!$commission_info){
                return false;
            }
        }else{
            $commission_info['platform_commission'] = $total_price;
            $commission_info['supplier_commission'] = 0;
            $commission_info['privileg_price']      = Model_Member_Order::order_privileg_price($order_info['id'],$order_info);
            $commission_info['ebooking_profit']     = 0;
        }
        $fx_info = array(
            'fx_self' => 0,
            'fx_top1' => 0,
            'fx_top2' => 0,
            'fx_top3' => 0,
        );
        //排除的typeid
        $exclude_typeids = [15];
        if ($order_info['memberid']) {
            if(St_Functions::is_normal_app_install('mobiledistribution') && !in_array($order_info['typeid'],$exclude_typeids) && $order_info['channel_id']==1){
                $is_fx = DB::select()->from('fenxiao')->where("memberid={$order_info['memberid']}")->execute()->current();
                if($is_fx){
                    $order_info['platform_commission'] = $commission_info['platform_commission'];
                    $res = Model_Fenxiao::get_order_fenxiao_info($order_info);
                    $fx_info['fx_self'] = sprintf("%.2f", $res['commission']);
                    $fx_info['fx_top1'] = sprintf("%.2f", $res['commission1']);
                    $fx_info['fx_top2'] = sprintf("%.2f", $res['commission2']);
                    $fx_info['fx_top3'] = sprintf("%.2f", $res['commission3']);
                }
            }
        }
        $c_shop_profit = 0;
        if($order_info['channel_id']==2){
            $c_shop_profit = DB::select()->from('c_shop_amount_log')->where("order_sn={$order_info['ordersn']}")->execute()->get('amount');
        }

        $fx_commission = array_sum($fx_info);
        $platform_profit = bcsub($commission_info['platform_commission'],$fx_commission,2);
        $platform_profit = bcsub($platform_profit,$commission_info['privileg_price'],2);
        $platform_profit = bcadd($platform_profit,$commission_info['ebooking_profit'],2);

        $member_card = 0;
        if(St_Functions::is_normal_app_install('system_card')){
            $card_privileg = DB::select()->from('card_member_reservation_record')->where("order_sn='{$order_info['ordersn']}'")->execute()->get('deductible_amount');
            $member_card = $card_privileg>0?$card_privileg:0;
        }

        $data = array(
            'order_id'               => $order_info['id'],
            'total_price'            => $total_price,//订单总价
            'privileg_price'         => $commission_info['privileg_price'],//优惠总额
            'subscription_price'     => $subscription_price,//定金金额
            'platform_commission'    => $commission_info['platform_commission'],//平台佣金 与供应商进行分佣
            'supplier_commission'    => $commission_info['supplier_commission'],//供应商佣金  与平台进行分佣
            'c_shop_profit'          => $c_shop_profit,//云店收益
            'fx_self'                => $fx_info['fx_self'],//分销自购收益
            'fx_top1'                => $fx_info['fx_top1'],//分销上一级佣金
            'fx_top2'                => $fx_info['fx_top2'],//分销上二级佣金
            'fx_top3'                => $fx_info['fx_top3'],//分销上三级佣金
            'platform_profit'        => $platform_profit,//平台收益 平台佣金减去各种优惠及分销商分佣 存在平台亏损
            'additional_total_price' => 0, //附加产品总价
            'ebooking_profit'        => $commission_info['ebooking_profit'], //附加产品总价
            'member_card'            => $member_card,
        );
        DB::insert('member_order_compute',array_keys($data))->values(array_values($data))->execute();

        if($commission_info['settlement_type']){
            //记录下单时，平台与供应商之间的结算类型
            $settlement_record = array(
                'order_id'         => $order_info['id'],
                'channel_id'       => $order_info['channel_id'],
                'settlement_type'  => $commission_info['settlement_type'],
                'commission_type'  => $commission_info['commission_type'],
                'commission_ratio' => $commission_info['commission_ratio'],
            );
            DB::insert('member_order_settlement',array_keys($settlement_record))->values(array_values($settlement_record))->execute();
        }
    }

    /**
     * @function 总价,优惠价,佣金更新
     * @param $ordersn string 订单号
     */
    public static function update($ordersn)
    {
        if ($ordersn) {
            $order_info = DB::select()->from('member_order')->where("ordersn", "=", "{$ordersn}")->execute()->current();
            switch ($order_info['typeid']) {
                case 14:
                    $data = array(
                        'total_price' => $order_info['price'],
                        'privileg_price' => 0,
                        'platform_profit' => $order_info['price'],
                    );
                    break;
                case 23:
                    self::combination_order_update($order_info);
                    break;
                default:
                    if ($order_info['haschild']) {
                        $data = self::update_multiple_order_compute($order_info);
                    } else {
                        $data = self::update_single_order_compute($order_info);
                    }
                    break;
            }

            if (!empty($data)) {
                DB::update('member_order_compute')->set($data)->where('order_id', '=', $order_info['id'])->execute();
            }
        }
    }

    /**
     * 更新父子订单的佣金信息
     * @param $order_info
     * @return array
     */
    public static function update_multiple_order_compute($order_info)
    {
        $commission_info = DB::select()
            ->from('member_order_compute')
            ->where("order_id", "=", "{$order_info['id']}")
            ->execute()
            ->current();

        // 分销商收益
        $fx_commission = array($commission_info['fx_self'], $commission_info['fx_top1'], $commission_info['fx_top2'], $commission_info['fx_top3']);
        $fx_commission = array_sum($fx_commission);

        // 主订单优惠金额
        $privilege_price = Model_Member_Order::order_privileg_price($order_info['id'], $order_info);

        // 订单总金额
        $price = $order_info['price'];

        // 子订单
        $sub_orders = DB::select('b.*')
            ->from(array('member_order', 'a'))
            ->join(array('member_order_compute', 'b'), 'right')
            ->on('a.id', '=', 'b.order_id')
            ->where('a.pid','=',$order_info['id'])
            ->execute()
            ->as_array();
        $platform_commission = 0;
        $supplier_commission = 0;

        $fx_self = 0;
        $fx_top1 = 0;
        $fx_top2 = 0;
        $fx_top3 = 0;
        foreach ($sub_orders as $sub_order) {
            $platform_commission = bcadd($platform_commission, $sub_order['platform_commission'], 2);
            $supplier_commission = bcadd($supplier_commission, $sub_order['supplier_commission'], 2);
            $privilege_price     = bcadd($privilege_price, $sub_order['privileg_price'], 2);

            $fx_self+=$sub_order['fx_self'];
            $fx_top1+=$sub_order['fx_top1'];
            $fx_top2+=$sub_order['fx_top2'];
            $fx_top3+=$sub_order['fx_top3'];
        }

        $platform_profit = bcsub($platform_commission, $privilege_price, 2);
        $platform_profit = bcsub($platform_profit, $fx_commission, 2);
        return array(
            'total_price' => $price,
            'privileg_price' => $privilege_price,
            'platform_commission' => $platform_commission,
            'supplier_commission' => $supplier_commission,
            'platform_profit' => $platform_profit,

            'fx_self' => $fx_self,
            'fx_top1' => $fx_top1,
            'fx_top2' => $fx_top2,
            'fx_top3' => $fx_top3,
        );
    }

    /**
     * 更新单个订单的佣金信息
     * @param $order_info
     * @return array
     */
    public static function update_single_order_compute($order_info)
    {
        $order_id = $order_info['id'];
        $commission_info = self::get_commission($order_id);

        $fx_commission   = array($commission_info['fx_self'], $commission_info['fx_top1'], $commission_info['fx_top2'], $commission_info['fx_top3']);
        $platform_profit = bcsub($commission_info['platform_commission'], array_sum($fx_commission), 2);
        $platform_profit = bcadd($platform_profit, $commission_info['ebooking_profit'], 2);
        $privilege_price = $commission_info['privileg_price'];

        /*获取总优惠金额*/
        $new_privileg_price = Model_Member_Order::order_privileg_price($order_id, $order_info);
        if ($order_info['channel_id'] == 3) {/*同业端单独处理*/
            $total_price = $commission_info['total_price'];
            if ($new_privileg_price != $commission_info['privileg_price']) {
                $privilege_price = $new_privileg_price;
            }
            $platform_profit = bcsub($platform_profit, $privilege_price, 2);
        } else {
            $platform_profit = bcsub($platform_profit, $new_privileg_price, 2);
            $privilege_price = $new_privileg_price;
            $total_price     = bcadd($commission_info['platform_commission'], $commission_info['supplier_commission'], 2);

            /*订单来源为云店时，计算价格浮动后平台的收益*/
            if ($order_info['channel_id'] == 2) {
                $c_order_price   = Model_Member_Order::order_total_price($order_id, $order_info);
                $org_order_price = Model_Admin_Cshop::get_org_total_price($order_info);
                $diff_price      = bcsub($c_order_price, $org_order_price, 2);//平台与店铺的差价
                if (!empty($diff_price)) {
                    $total_price = $c_order_price;
                }
            }
        }
        //保险金额累加
        $insurance_order = DB::select()->from('member_order')
            ->where('pid','=',$order_id)
            ->and_where('typeid','=',111)
            ->execute()->as_array();
        if(count($insurance_order)>0){
            foreach ($insurance_order as $v) {
                $insurance_price = DB::select()->from('member_order_compute')->where('order_id','=',$v['id'])->execute()->get('total_price');
                $total_price = bcadd($total_price, $insurance_price, 2);
            }
        }

        return array(
            'total_price' => $total_price,
            'privileg_price' => $privilege_price,
            'platform_profit' => $platform_profit,
        );
    }

    /**
     * @param $order_info
     * @param false $total_price
     * @return false|int|int[]|mixed
     * 计算平台与供应商的佣金信息
     */
    public static function caculate_platform_commission($order_info, $total_price=false)
    {
        if($total_price===true){
            /*计算预估收益*/
            $estimated_income = self::get_estimated_income($order_info);
            return $estimated_income;
        }
        $commission = array(
            'platform_commission'  => 0,
            'supplier_commission'  => 0,
            'privileg_price'       => 0,
            'settlement_type'      => 0,//结算类型
            'commission_type'      => 0,//抽佣类型
            'commission_ratio'     => 0,//抽佣 比例或金额
            'ebooking_profit'      => 0,//抽佣 比例或金额
        );

        //检测财务是否安装.
        if(!self::is_finance_install()) {
            return $commission;
        }

        try {
            /*同业端比较特殊  单独处理*/
            if($order_info['channel_id']==3){
                $commission = self::ebooking_commission($order_info, $commission);
                return $commission;
            }
            $type_id = $order_info['typeid'];
            $table = St_Functions::table_field($type_id);
            if(in_array($type_id,array(8,13,104))){
                //签证与团购应用没有suit_id,佣金配置按产品id关联
                $suit_id = $order_info['productautoid'];
            }else{
                $suit_id = $order_info['suitid'];
            }
            $channel_id = $order_info['channel_id'];
            $suit_info = DB::select()->from($table[0])->where("id={$suit_id}")->execute()->current();

            $commission['privileg_price'] = Model_Member_Order::order_privileg_price($order_info['id'],$order_info);

//            if(St_Functions::is_normal_app_install('seckill')){
//                /*如果是秒杀订单，总价加上秒杀优惠的金额，再计算与供应商之间的分佣*/
//                $seckill_privileg = Model_Seckill::get_privileg_price($order_info);
//                $total_price = bcadd($total_price,$seckill_privileg,2);
//            }
            if($order_info['pid']){
                $top_order = DB::select()->from('member_order')->where("id={$order_info['pid']}")->execute()->current();
                if($top_order['typeid']==23){
                    /*如果是组合订单的话，总价需加上或减去浮动的金额，再计算平台与供应商之间的分佣*/
                    $total_price = Model_Combination_Price::calculation_original_price($order_info);
                }
            }
            if($order_info['channel_id']==2){
                /*如果是云店过来的订单，总价需加上或减去浮动的金额，再计算平台与供应商之间的分佣*/
                $total_price = Model_Admin_Cshop::get_org_total_price($order_info);
                if(!$total_price){
                    return false;
                }
            }
            //默认结算价结算
            if($suit_info['settlement_type']==1 || !isset($suit_info['settlement_type'])){
                $model_class_name = "Model_".ucfirst($table[3]);
                $order_profit = call_user_func(array($model_class_name,'get_order_profit'),$order_info);
                $commission['platform_commission'] = $order_profit;
                $commission['supplier_commission'] = bcsub($total_price,$commission['platform_commission'],2);
                $commission['commission_type'] = 3;
                $commission['commission_ratio'] = $order_profit;
            }else{
                /*获取平台与供应商的结算配置*/
                $settlement_cfg = DB::select()->from('supplier_settlement_config')
                    ->where("type_id={$type_id} and suit_id={$suit_id} and channel_id={$channel_id}")
                    ->execute()->current();
                if(!$settlement_cfg){
                    //没有结算配置时，供应商佣金=订单总价
                    $commission['supplier_commission'] = $total_price;
                    return $commission;
                }
                $commission['commission_type'] = $settlement_cfg['settlement_key'];
                $commission['commission_ratio'] = $settlement_cfg['settlement_val'];
                if($settlement_cfg['settlement_key']==1){
                    $commission['platform_commission'] = bcmul($total_price,$settlement_cfg['settlement_val'],2);
                    $commission['supplier_commission'] = bcsub($total_price,$commission['platform_commission'],2);
                }else{
                    $commission['platform_commission'] = $settlement_cfg['settlement_val'];
                    $commission['supplier_commission'] = bcsub($total_price,$commission['platform_commission'],2);
                }
            }
            $commission['settlement_type'] = $suit_info['settlement_type'];
            return $commission;
        }
        catch (Exception $e)
        {
            return false;
        }
    }

    public static function ebooking_commission($order_info, $commission_arr)
    {
        $good_list = DB::select()->from('member_order_goods')->where("order_id={$order_info['id']}")->execute()->as_array();
        if(!$good_list){
            return $commission_arr;
        }
        $ebooking_profit     = 0;
        $ebooking_discount   = 0;
        $platform_commission = 0;
        $supplier_commission = 0;
        $settlement_type_arr = array();
        $commission_type_arr = array();
        $commission_ratio_arr= array();
        foreach ($good_list as $k=>$v){
            /*获取结算类型*/
            $settlement_type = DB::select()->from('hotel_room')->where("id={$v['suit_id']}")->execute()->get('settlement_type');
            /*获取下单时套餐详细信息*/
            $goods_time = DB::select()->from('member_order_goods_time')->where("goods_id={$v['id']}")->execute()->current();
            $price_detailed = array_sum(explode(',',$goods_time['price_detailed']));
            $profit_detailed = array_sum(explode(',',$goods_time['profit_detailed']));
            $original_price = bcmul($goods_time['number'],$price_detailed,2);
            $original_profit = bcmul($goods_time['number'],$profit_detailed,2);

            if($settlement_type==1){/*结算价模式*/
                /*记录抽佣方式*/
                $commission_type_arr[$k][$v['suit_id']] = 3;

                /*记录结算比例或固定金额*/
                $commission_ratio_arr[$k][$v['suit_id']] = $profit_detailed;

                /* 供应商佣金= 产品原价*预订数量-产品利润*预订数量 */
                $supplier_commission = bcadd($supplier_commission, bcsub($original_price, $original_profit,2),2);

                /* 平台佣金= 产品利润*预订数量 */
                $platform_commission = bcadd($platform_commission,bcmul($goods_time['number'],$profit_detailed,2),2);
            }else{/*销售价模式*/
                /*获取抽佣类型*/
                $commission_type = DB::select()->from('supplier_settlement_config')->where("type_id={$order_info['typeid']} and suit_id={$v['suit_id']}")->execute()->current();
                if($commission_type['settlement_key']==1){
                    /*比例抽佣*/
                    $commission = bcmul($original_price,$commission_type['settlement_val'],2);
                    $platform_commission = bcadd($platform_commission,$commission,2);

                    /*记录抽佣方式*/
                    $commission_type_arr[$k][$v['suit_id']] = 1;
                }else{
                    /*固定金额抽佣*/
                    $commission = bcmul($goods_time['number'],$commission_type['settlement_val'],2);
                    $platform_commission = bcadd($platform_commission,$commission,2);

                    /*记录抽佣方式*/
                    $commission_type_arr[$k][$v['suit_id']] = 2;
                }
                /*记录结算比例或固定金额*/
                $commission_ratio_arr[$k][$v['suit_id']] = $commission_type['settlement_val'];

                /* 供应商佣金= 原价*预订数-平台抽佣 */
                $supplier_commission = bcadd($supplier_commission,bcsub($original_price,$commission,2),2);
            }
            /*记录结算类型*/
            $settlement_type_arr[$k][$v['suit_id']] = $settlement_type;

            /*同业端优惠价*/
            $ebooking_discount = bcadd($ebooking_discount,$goods_time['reduction_amount'],2);

            /*同业端利润= 同业总价-原价-子社采购后向主社产生的佣金  会存在负数*/
            $ebooking_profit = bcadd($ebooking_profit,bcsub($goods_time['total_price'],$original_price,2),2);
            $ordersn = DB::select()->from("member_order")->where("id={$v['order_id']}")->execute()->get('ordersn');
            $purchaser_commission = DB::select()->from("member_order_goods_commission")->where("ordersn={$ordersn}")->execute()->get('commission');
            $ebooking_profit = bcsub($ebooking_profit,$purchaser_commission,2);
        }

        $commission_arr['platform_commission'] = $platform_commission;
        $commission_arr['ebooking_profit']     = $ebooking_profit;
        $commission_arr['supplier_commission'] = $supplier_commission;
        $commission_arr['privileg_price']      = $ebooking_discount;
        $commission_arr['settlement_type']     = json_encode($settlement_type_arr);
        $commission_arr['commission_type']     = json_encode($commission_type_arr);
        $commission_arr['commission_ratio']    = json_encode($commission_ratio_arr);
        return $commission_arr;
    }

    /**
     * @param $order
     * @return false|int|mixed
     * 计算预估收益
     */
    public static function get_estimated_income($order)
    {
        if(St_Functions::is_normal_app_install('mobiledistribution')){
            $commission_type_field = 'cfg_fenxiao_commission_type_'.$order['typeid'];
            $commission_type = DB::select()->from('fenxiao_config')
                ->where("varname='{$commission_type_field}'")
                ->execute()->get('value');
            if($commission_type==2){
                $model_info = DB::select()->from('model')->where('id','=',$order['typeid'])->execute()->current();
                $main_table = $model_info['maintable'];


                $model_class_name =ucfirst($main_table);
                if(strpos($main_table,'_')!==false)
                {
                    $main_table_piece = explode('_',$main_table);
                    foreach($main_table_piece as &$piece)
                    {
                        $piece = ucfirst($piece);
                    }
                    $model_class_name = implode('_',$main_table_piece);
                }

                $model_class_name = 'Model_'.$model_class_name;
                $gbl_commisson_cash = 0;

                if(class_exists($model_class_name) && method_exists($model_class_name,'get_order_profit'))
                {
                    $gbl_commisson_cash = call_user_func(array($model_class_name,'get_order_profit'),$order);
                    $gbl_commisson_cash = doubleval($gbl_commisson_cash)> doubleval($order['totalprice'])? $order['totalprice']:$gbl_commisson_cash;
                }
                //通用产品
                else if($model_class_name == 'Model_Archive')
                {
                    $gbl_commisson_cash = call_user_func(array('Model_Tongyong','get_order_profit'),$order);
                    $gbl_commisson_cash = doubleval($gbl_commisson_cash)> doubleval($order['totalprice'])? $order['totalprice']:$gbl_commisson_cash;
                }

                return $gbl_commisson_cash;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }

    public static function combination_order_update($order_info)
    {
        $sub_order                 = DB::select()->from('member_order')->where("pid={$order_info['id']}")->execute()->as_array();
        $platform_total_profit     = 0;
        $platform_total_commission = 0;
        $total_price               = 0;
        $total_supplier_commission = 0;
        foreach ($sub_order as $v) {
            $order_compute = DB::select()->from('member_order_compute')->where("order_id={$v['id']}")->execute()->current();
            //平台要承担,从分佣中扣除的金额
            $deduction       = array_sum(array(
                $order_compute['privileg_price'],
                $order_compute['supplier_commission'],
                $order_compute['fx_self'],
                $order_compute['fx_top1'],
                $order_compute['fx_top2'],
                $order_compute['fx_top3'],
            ));
            $platform_profit = bcsub($order_compute['total_price'], $deduction, 2);
            DB::update('member_order_compute')->set(array('platform_profit' => $platform_profit))->where("id={$order_compute['id']}")->execute();
            $platform_total_profit     = bcadd($platform_total_profit, $platform_profit, 2);
            $total_price               = bcadd($total_price, $order_compute['total_price'], 2);
            $total_supplier_commission = bcadd($total_supplier_commission, $order_compute['supplier_commission'], 2);
            $platform_total_commission = bcadd($platform_total_commission, $order_compute['platform_commission'], 2);
        }
        $order_compute = DB::select()->from('member_order_compute')->where("order_id={$order_info['id']}")->execute()->current();
        $fx = array_sum([
            $order_compute['fx_self'],
            $order_compute['fx_top1'],
            $order_compute['fx_top2'],
            $order_compute['fx_top3'],
        ]);
        $platform_total_profit = bcsub($platform_total_profit,$fx,2);
        DB::update('member_order_compute')->set(array(
            'total_price'         => $total_price,
            'platform_profit'     => $platform_total_profit,
            'supplier_commission' => $total_supplier_commission,
            'platform_commission' => $platform_total_commission
        ))->where("order_id={$order_info['id']}")->execute();
    }

    /**
     * @function 获取附加产品总价.
     * @param $pid
     * @return int|mixed
     */
    public static function caculate_additional_price($pid)
    {
        $addtional_total_price = 0;
        $additional = DB::select()->from('member_order')->where('pid','=',$pid)->execute()->as_array();

        if($additional)
        {
            foreach($additional as &$sub)
            {

                $sub_price = Model_Member_Order::order_total_price($sub['id']);
                $addtional_total_price+= $sub_price;
            }

        }
        return $addtional_total_price;
    }

    /**
     * @function 是否计算过订单信息.
     * @param $order_id
     * @return int
     */
    public static function is_computed($order_id)
    {
        $row = DB::select('id')->from('member_order_compute')->where('order_id','=',$order_id)->execute()->as_array();
        return $row['id'] ? $row['id'] : 0;
    }

    /**
     * @function
     * @param $order_id
     * @return array 返回计算的订单佣金,收益信息.
     */
    public static function get_income_info($order_id)
    {
        $out = array();
        $info = DB::select()->from('member_order_compute')->where('order_id','=',$order_id)->execute()->current();
        if($info)
        {
            $out['supplier_income'] = $info['supplier_commission'];
            //平台收益 = 平台佣金-优惠金额+附加产品金额
            $out['platform_income'] = $info['platform_profit'];
            //平台佣金
            $out['platform_commission'] = $info['platform_commission'];
            //尾款 = 订单总额-定金总额
            if($info['subscription_price'])
            {
                $out['left_price'] = $info['total_price'] - $info['subscription_price'];

            }
            //分销收益
            if(St_Functions::is_normal_app_install('mobiledistribution'))
            {
                //获取当前订单分销的信息...
                $out['fenxiao'] = array();

            }
        }
        return $out;
    }

    /**
     * @function 订单计算好的结果.
     * @param $order_id
     * @return array
     */
    public static function get_order_price($order_id)
    {
        $row = DB::select()->from('member_order_compute')->where('order_id','=',$order_id)->execute()->current();
        if($row)
        {
            if($row['subscription_price'] ==0)
            {
                //支付价格 = 总价-优惠价
                $row['pay_price'] = $row['total_price'] - $row['privileg_price'];
            }
            else
            {    //支付价格 = 订金总价-优惠价 定金金额存在是
                $row['pay_price'] = $row['subscription_price'];
            }
            //如果支付金额大于订单总额,则支付金额为订单总额.
            if($row['pay_price'] > $row['total_price'])
            {
                $row['pay_price'] = $row['total_price'];
            }
            //如果支付金额小于0,则置为0
            if($row['pay_price'] < 0)
            {
                $row['pay_price'] = 0;
            }
            //浮点精度修复
            $row['pay_price']=floatval(number_format($row['pay_price'],2,'.',''));
        }
        return $row ? $row : array();
    }

    /**
     * @function 获取子订单佣金信息.
     * @param $pid
     * @return array
     */
    private static function get_sub_info($pid)
    {
        //检测是否有子订单
        $sub_orders = DB::select()->from('member_order')->where('pid','=',$pid)->execute()->as_array();
        //子订单金额
        $sub_total_price = 0;
        //子订单佣金
        $supplier_commission =  0;
        //子订单优惠
        $privileg_price = 0;
        if($sub_orders)
        {
            foreach($sub_orders as $order)
            {
                $sub_member_order_compute = DB::select()->from('member_order_compute')->where("order_id={$order['id']}")->execute()->current();
                $sub_total_price += Model_Member_Order::order_total_price($order['id'],$order);
                $commission = self::caculate_platform_commission($order,true);
                $supplier_commission += $commission['supplier_commission'];
                if($sub_member_order_compute){
                    $privileg_price += $sub_member_order_compute['privileg_price'];
                }else{
                    $privileg_price += $order['privileg_price'];
                }
            }
        }
        return array(
            'total_price' => $sub_total_price,
            'supplier_commission' => $supplier_commission,
            'privileg_price' => $privileg_price
        );
    }

    /**
     * @function 检测财务是否安装.
     * @return bool
     */
    private static function is_finance_install()
    {
        $table_name = 'sline_supplier_commission_product';
        $result = DB::query(1,"SHOW TABLES LIKE '{$table_name}'")->execute()->as_array();
        if($result[0] && St_Functions::is_normal_app_install('system_finance'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //更新退款手续费
    public static function update_refund_cost($orderid,$refund_cost)
    {
        return DB::query(Database::UPDATE,"update sline_member_order_compute set refund_cost='$refund_cost' where order_id='{$orderid}'")->execute();
    }

    /**
     * @function 添加佣金记录
     * @param $order
     */
    public static function add_commission_record($order_id,$comission_cash,$commission_type,$commission_ratio)
    {
        //检测财务应用是否安装
        if(!self::is_finance_install())
        {
            return false;
        }

        $data = array(
            'order_id' => $order_id,
            'commission_cash' => $comission_cash,
            'commission_type' => $commission_type,
            'commission_ratio' => $commission_ratio,
            'addtime' => time()
        );
        $row = DB::select('order_id')->from('supplier_commission_record')
            ->where('order_id','=',$order_id)
            ->execute()
            ->current();
        if(isset($row['order_id']) && $row['order_id'])
        {
            DB::update('supplier_commission_record')->set($data)->where('order_id','=',$order_id)->execute();
        }
        else
        {
            DB::insert('supplier_commission_record',array_keys($data))->values(array_values($data))->execute();
        }
    }

    /**
     * @param $order_id
     * @return mixed|null
     * 获取佣金详情
     */
    public static function get_commission($order_id)
    {
        return DB::select()->from('member_order_compute')->where("order_id", "=", $order_id)->execute()->current();
    }
}